package com.lindroy.androidplayer.ui.search

import android.os.Bundle
import android.view.View
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.paging.map
import com.lindroy.androidplayer.base.BaseFragment
import com.lindroy.androidplayer.base.BaseListFragment
import com.lindroy.androidplayer.databinding.FragmentSearchResultBinding
import com.lindroy.androidplayer.ui.adapter.ArticleAdapter
import com.lindroy.androidplayer.ui.webview.WebViewFragment
import com.lindroy.androidplayer.utils.KVUtil
import com.lindroy.androidplayer.utils.addSimpleDivider
import com.lindroy.androidplayer.utils.collectListWhenResumed
import com.lindroy.androidplayer.viewmodels.SearchResultViewModel
import com.lindroy.lib_utils.extensions.hideKeyboard

/**
 * @author Lin
 * @date 2022/3/8
 * @function 搜索结果页面
 */
class SearchResultFragment :
    BaseListFragment<FragmentSearchResultBinding, SearchResultViewModel>() {

    private val resultArgs by navArgs<SearchResultFragmentArgs>()

    private val keyword by lazy { resultArgs.keyword }

    private val adapter by lazy { ArticleAdapter(viewLifecycleOwner) }

    override fun FragmentSearchResultBinding.initView(savedInstanceState: Bundle?) {
        vm = mViewMode
        rvResult.addSimpleDivider()
        rvResult.adapter = adapter.withFooter()
        rvResult.hideKeyboard()
    }

    override fun FragmentSearchResultBinding.initListener() {
        mViewMode.setLayoutStateFlow(adapter.loadStateFlow)
        mViewMode.getSearchResult(keyword).collectListWhenResumed(viewLifecycleOwner) {
            adapter.submitData(it)
        }
        mViewMode.itemClickLiveData.observe(viewLifecycleOwner) {
            WebViewFragment.start(this@SearchResultFragment, it.id, it.link, it.title, it.collect)
        }
    }

    override fun onRefresh() {
        adapter.refresh()
    }

    override fun onRetry(view: View) {
        adapter.retry()
    }

    companion object {
        fun start(fragment: BaseFragment<*>, keyword: String) {
            start( fragment.findNavController(),keyword)
        }

        fun start(navController: NavController, keyword: String) {
            navController.navigate(
                SearchResultFragmentDirections.actionToSearchResult(
                    keyword
                )
            )
        }
    }
}